package me.firstapp.manage.login;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.json.SingleObject;
import me.firstapp.common.module.system.JsonOperator;
import me.firstapp.common.utils.ResponseUtils;
import me.firstapp.common.utils.StrUtils;
import me.firstapp.manage.common.BaseManage;
import me.firstapp.spi.system.OperatorService;

@Controller
@RequestMapping(value = "/loginManage")
public class LoginManageAct extends BaseManage {

	@Autowired
	private OperatorService operatorService;

	@RequestMapping(value = "/login.do", method = RequestMethod.POST)
	public void login(String name, String password, String code, HttpServletRequest request, HttpServletResponse response) {
		SingleObject<JsonOperator> result = operatorService.login(name, password, code);
		if (StatusHouse.COMMON_STATUS_OK.getCode().equals(result.getCode())) {
			String loginToken = StrUtils.getLoginToken();
			request.getSession().setAttribute("loginToken", loginToken);
			request.getSession().setAttribute("login_operator_" + loginToken, result.getObject());
		}
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping(value = "/logout.do", method = RequestMethod.POST)
	public void logout(String account, HttpServletRequest request, HttpServletResponse response) {
		SingleObject<Object> result = new SingleObject<>();
		String loginToken = (String) request.getSession().getAttribute("loginToken");
		request.getSession().removeAttribute("loginToken");
		request.getSession().removeAttribute("login_operator_" + loginToken);
		result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
		ResponseUtils.renderJson(response, result);
	}
}
